package net.omnivention.proxy;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

//import javax.net.SocketFactory;
//import javax.net.ssl.SSLSocketFactory;

import org.apache.log4j.Logger;

public class ProxyConnector implements Runnable {
	private static Logger logger = Logger.getLogger(ProxyConnector.class);

	private Socket clientSocket;

	public ProxyConnector(Socket clientSocket) {
		this.clientSocket = clientSocket;
	}

	public void run() {
		try {
			InputStream clientInputStream = clientSocket.getInputStream();
			BufferedInputStream clientBufferedInputStream = new BufferedInputStream(clientInputStream);

			HttpRequest request = HttpUtility.parseRequest(clientBufferedInputStream);
			logger.info("\n"+request);
			String host = request.getHost();
			int port = request.getPort();
			logger.info("connecting to " + host + ":" + port);

			Socket hostSocket;
//			String method = request.getMethod();
//			if (HttpRequest.CONNECT.equals(method)) {
//				SocketFactory socketFactory = SSLSocketFactory.getDefault();
//				hostSocket = socketFactory.createSocket(host, PORT);
//			} else {
//				hostSocket = new Socket(host, PORT);
//			}
			
			hostSocket = new Socket(host, port);
			ClientToHost c2h = new ClientToHost(request, clientSocket, hostSocket);
			Thread t1 = new Thread(c2h);
			t1.start();

			HostToClient h2c = new HostToClient(request, clientSocket, hostSocket);
			Thread t2 = new Thread(h2c);
			t2.start();

		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
	}

}
